# -*- coding: utf-8 -*-
"""
@Time    : 2021/10/9 17:51
@Author  : Leibuyun
@File    : 1.15 通过某个字段将记录分组.py
"""

from operator import itemgetter
from itertools import groupby

if __name__ == '__main__':
    rows = [
        {'address': '5412 N CLARK', 'date': '07/01/2012'},
        {'address': '5148 N CLARK', 'date': '07/04/2012'},
        {'address': '5800 E 58TH', 'date': '07/02/2012'},
        {'address': '2122 N CLARK', 'date': '07/03/2012'},
        {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
        {'address': '1060 W ADDISON', 'date': '07/02/2012'},
        {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
        {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
    ]

    rows.sort(key=itemgetter('date'))  # 先根据date排序（后续通过date分组）
    # groupby()函数扫描整个序列并且查找连续相同值的元素序列，在每次迭代的时候，返回一个值和一个迭代器对象
    for date, items in groupby(rows, key=itemgetter('date')):
        print(date)
        for i in items:
            print(' ', i)
